<?php
class WishCrawler {
  private static $cookie;

  public static function init() {
    self::$cookie = 'session="'.WISH_COOKIE_SSID.'"; session0="'.WISH_COOKIE_SSID2.'"; remember_me='.WISH_COOKIE_REMEMBER.'; bsid='.WISH_COOKIE_BSID;
  }

  public static function crawlHistoryOrders() {
    self::init();

    $url = "http://merchant.wish.com/api/merchant/transactions/get";
    $params = "start=0&count=500&attention=false&label_ready=false&ack=false&sort=last_update&query=&filter=&start_date=&end_date=&order=desc&search_type=order_id&is_wlc=false&include_tickets=true&label_downloaded=false&hide_count=false";
    $headers = array( 
      "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Cache-Control: no-cache",
      "Pragma: no-cache",
      'Cookie: '.self::$cookie,
    );

    $result = '';
    $try = 0;
    do {
      $try++;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 60);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36');
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
      if (USE_PROXY) {
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:10800");        
      }
      $result = curl_exec($ch);
      if (curl_errno($ch)) {
        continue;
      } else {
        curl_close($ch);
        break;
      }     
    } while ($try < 3);

    if (empty($result)) {
      return false;
    }

    $result = json_decode($result, true);
    return $result['data']['results'];
  }
  
  public static function crawlTicket($ticketId) {
    self::init();

    $url = "http://merchant.wish.com/ticket/{$ticketId}";
    $headers = array( 
      "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Cache-Control: no-cache",
      "Pragma: no-cache",
      'Cookie: '.self::$cookie,
    );

    $result = '';
    $try = 0;
    $curlError = '';
    do {
      $try++;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 60);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36');
      if (USE_PROXY) {
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:10800");        
      }
      $result = curl_exec($ch);
      if (curl_errno($ch)) {
        $curlError = curl_error($ch);
        continue;
      } else {
        curl_close($ch);
        break;
      }     
    } while ($try < 3);

    if (empty($result)) {
      throw new Exception("crawler failed.".$curlError);
      return false;
    }

    preg_match("/.*window.pageParams = {(.*)}.*/", $result, $matches);
    $pageParams = json_decode("{{$matches[1]}}", true);

    // extract ticket info
    return $pageParams['ticket'];
  }

  public static function crawlTicketDetail($ticketId) {
    self::init();

    $url = "http://merchant.wish.com/ticket/{$ticketId}";
    $headers = array( 
      "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Cache-Control: no-cache",
      "Pragma: no-cache",
      'Cookie: '.self::$cookie,
    );

    $result = '';
    $try = 0;
    do {
      $try++;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 60);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36');
      if (USE_PROXY) {
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:10800");
      }
      $result = curl_exec($ch);
      if (curl_errno($ch)) {
        continue;
      } else {
        break;
      }     
    } while ($try < 3);

    // 一旦出错即停止运行，保护数据完整性
    if (empty($result)) {
      $errMsg = curl_errno($ch);
      curl_close($ch);
      return array(1, $errMsg, null);
    }

    preg_match("/.*window.pageParams = {(.*)}.*/", $result, $matches);
    $pageParams = json_decode("{{$matches[1]}}", true);

    // extract ticket info
    return array(0, '', $pageParams['ticket']);
  }

  public static function crawlTickets() {
    self::init();

    $ticketStatusFilter = array(
      'Awaiting+User',
      'Action+Required',
      'Closed',
    );

    $tickets = array();
    $url = "http://merchant.wish.com/api/tickets/get";
    foreach ($ticketStatusFilter as $filter) {
      $count = 100;
      $total = PHP_INT_MAX;
      $ticketCollection = array();
      for ($start=0; $start < $total; $start += $count) {
        $params = "start={$start}&count={$count}&query=&filter={$filter}&sort=update_date&order=asc&fbw_filter=false";
        $headers = array( 
          "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
          "Cache-Control: no-cache",
          "Pragma: no-cache",
          'Cookie: '.self::$cookie,
        );

        $try = 0;
        do {
          $try++;
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_TIMEOUT, 60);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36');
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
          if (USE_PROXY) {
            curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
            curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:10800");            
          }
          $result = curl_exec($ch);
          if (curl_errno($ch)) {
            continue;
          } else {
            curl_close($ch);
            break;
          }     
        } while ($try < 3);

        // 一旦出错即停止运行，保护数据完整性
        if (empty($result)) {
          return array(1, curl_errno($ch), null);
        }

        // 数据获取失败？
        $result = json_decode($result, true);
        if (empty($result['data'])) {
          return array($result['code'], $result['msg'], null);
        }

        $total = $result['data']['results']['num_results'];
        $ticketCollection = array_merge($ticketCollection, $result['data']['results']['rows']);
      }
      $tickets[$filter] = $ticketCollection;
    }
    return array(0, '', $tickets);
  }

  public static function crawlRepliedTickets() {
    self::init();
    
    $url = "http://merchant.wish.com/api/tickets/get";
    $params = "start=0&count=500&query=&filter=Awaiting+User&sort=update_date&order=asc&fbw_filter=false";
    $headers = array(
      "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Cache-Control: no-cache",
      "Pragma: no-cache",
      'Cookie: '.self::$cookie,
    );

    $result = '';
    $try = 0;
    $curlError = '';
    do {
      $try++;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 60);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36');
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
      if (USE_PROXY) {
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:10800");        
      }
      $result = curl_exec($ch);
      if (curl_errno($ch)) {
        $curlError = curl_error($ch);
        continue;
      } else {
        curl_close($ch);
        break;
      }     
    } while ($try < 3);

    if (empty($result)) {
      throw new Exception("crawler failed.".$curlError);
      return false;
    }

    $result = json_decode($result, true);
    return $result['data']['results']['rows'];
  }

  public static function crawlTicketOrders() {
    $historyOrders = self::crawlHistoryOrders();
    $ticketOrders = array();
    if (!empty($historyOrders)) {
      foreach ($historyOrders as $order) {
        if (!empty($order['ticket_id'])) {
          $ticketOrders[$order['ticket_id']] = $order;
        }
      }     
    }
    return $ticketOrders;
  }
}